#include <stdint.h>
#include "tim.h"
#include "oslib.h"
#include "light.h"

#define LIGHT_PERIOD    (105)
#define LIGHT_ONE_DUTY  ((uint8_t)(0.48f * LIGHT_PERIOD))
#define LIGHT_ZERO_DUTY ((uint8_t)(0.24f * LIGHT_PERIOD))

static int light_number = 4;
static uint16_t light_duty_array[4*24+1] = {0};

static void light_rgb2duty(uint16_t *array, uint32_t grb)
{
    int i, j;
    for (i = 23, j = 0; i >= 0; i--, j++) {
        if (grb & (1 << i)) {
            array[j] = LIGHT_ONE_DUTY;
        }
        else {
            array[j] = LIGHT_ZERO_DUTY;
        }
    }
}

void light_set_color(uint8_t which, uint8_t R, uint8_t G, uint8_t B) 
{
    uint32_t grb = ((G << 16) | (R << 8) | (B << 0)); 
    if (which == 0) {
        for (int i = 0; i < light_number; i++) {
            light_rgb2duty(light_duty_array+24*i, grb);
        }
    }
    else if (which > 0 && which < light_number) {
        light_rgb2duty(light_duty_array+24*(which-1), grb);
    }
    else {
        uprintf("[Error] Wrong light number");
        return;
    }
    HAL_TIM_OC_Start_DMA(&htim3, TIM_CHANNEL_1, (uint32_t *)light_duty_array, sizeof(light_duty_array)/sizeof(uint16_t));
}

void HAL_TIM_PWM_PulseFinishedCallback(TIM_HandleTypeDef *htim)
{
    if (htim->Instance == TIM3) {
        HAL_TIM_OC_Stop_DMA(&htim3, TIM_CHANNEL_1);
    }
}
